package com.hust360.percent.pojo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.pojo.Area.AreaDAO;
import com.hust360.percent.utils.StorageUtils;

@SuppressLint("SimpleDateFormat")
public class AreaDAOImpl implements AreaDAO {

	private PercentApplication application;

	public AreaDAOImpl(Application application) {
		this.application = (PercentApplication) application;
	}

	@Override
	public Area findById(Long id) {
		Area area = null;
		final SimpleDateFormat format = StorageUtils.simpleDateFormat;
		Cursor cursor = application.getLocalDB().query(Area.TABLE, null,
				Area.ID + "='" + id + "'", null, null, null, null);
		if (cursor.moveToFirst()) {
			area = new AreaLocal();
			area.setId(cursor.getLong(cursor.getColumnIndex(Area.ID)));
			area.setImg(cursor.getString(cursor.getColumnIndex(Area.IMG)));
			area.setTitle(cursor.getString(cursor.getColumnIndex(Area.TITLE)));
			area.setType(cursor.getInt(cursor.getColumnIndex(Area.TYPE)));
			Date from = null;
			Date deadline = null;
			Date modify = null;
			try {
				from = format.parse(cursor.getString(cursor
						.getColumnIndex(Area.FROM)));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				e.printStackTrace();
			}

			try {
				deadline = format.parse(cursor.getString(cursor
						.getColumnIndex(Area.DEADLINE)));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				e.printStackTrace();
			}

			try {
				modify = format.parse(cursor.getString(cursor
						.getColumnIndex(Area.MODIFY)));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				e.printStackTrace();
			}

			area.setFromDate(from);
			area.setDeadline(deadline);
			area.setModifydate(modify);

		}
		cursor.close();
		return area;
	}

	@Override
	public void deleteById(Long id) {
		application.getLocalDB().delete(Area.TABLE, Area.ID + "=" + id, null);
	}

	@Override
	public List<Area> findByArgs(String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String orderBy) {
		final SimpleDateFormat format = StorageUtils.simpleDateFormat;
		Cursor c = application.getLocalDB().query(Area.TABLE, columns,
				selection, selectionArgs, groupBy, having, orderBy);

		ArrayList<Area> list = new ArrayList<Area>(c.getCount() + 5);
		Area area = null;
		while (c.moveToNext()) {
			area = new AreaLocal();

			area.setId(c.getLong(c.getColumnIndex(Area.ID)));
			area.setImg(c.getString(c.getColumnIndex(Area.IMG)));
			area.setTitle(c.getString(c.getColumnIndex(Area.TITLE)));
			area.setType(c.getInt(c.getColumnIndex(Area.TYPE)));
			Date from = null;
			Date deadline = null;
			Date modify = null;
			try {
				from = format.parse(c.getString(c.getColumnIndex(Area.FROM)));
			} catch (ParseException e) {
				e.printStackTrace();
			}

			try {
				deadline = format.parse(c.getString(c
						.getColumnIndex(Area.DEADLINE)));
			} catch (ParseException e) {
				e.printStackTrace();
			}

			try {
				modify = format
						.parse(c.getString(c.getColumnIndex(Area.MODIFY)));
			} catch (ParseException e) {
				e.printStackTrace();
			}

			area.setFromDate(from);
			area.setDeadline(deadline);
			area.setModifydate(modify);

			list.add(area);
		}
		c.close();
		return list;
	}

	@Override
	public void save(Area area) {

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		ContentValues values = new ContentValues();
		values.put(Area.ID, area.getId());
		values.put(Area.IMG, area.getImg());
		values.put(Area.TITLE, area.getTitle());
		values.put(Area.CITY_ID, area.getCityId());
		values.put(Area.TYPE, area.getType());
		values.put(Area.LONGITUDE_COLUMN, area.getLongitude());
		values.put(Area.LATITUDE_COLUMN, area.getLatitude());
		values.put(Area.NAME, area.getName());

		Date date = area.getModifydate();
		if (date != null) {
			values.put(Area.MODIFY, format.format(date));
		}

		date = area.getDeadline();
		if (date != null)
			values.put(Area.DEADLINE, format.format(date));

		date = area.getFromDate();
		if (date != null)
			values.put(Area.FROM, format.format(date));

		application.getLocalDB().insertWithOnConflict(Area.TABLE, null, values,
				SQLiteDatabase.CONFLICT_REPLACE);
	}

	@Override
	public List<Area> findWithMap(Map<String, String> map) {
		final SimpleDateFormat format = StorageUtils.simpleDateFormat;
		Set<String> keyset = map.keySet();
		final List<String> columns = Arrays.asList(Area.COLUMNS);
		String value;
		StringBuffer selection = new StringBuffer();
		List<Area> areas;
		Area area;
		SQLiteDatabase db = PercentApplication.localDB;
		Date deadline = null;
		Date moddate = null;
		Date startdate = null;

		for (String key : keyset) {
			value = map.get(key);
			if (columns.contains(key) && value != null) {
				selection.append(key + "='" + value + "' AND ");
			}
		}
		selection.append("'1'='1'");
		Cursor c = db.rawQuery(
				"SELECT * FROM Area WHERE " + selection.toString(), null);
		areas = new ArrayList<Area>(c.getCount());
		while (c.moveToNext()) {
			area = new AreaLocal();
			area.setCityId(c.getLong(c.getColumnIndex(AreaLocal.CITY_ID)));
			
			
			try {
				deadline = format.parse(c.getString(c.getColumnIndex(Area.DEADLINE)));
				area.setDeadline(deadline);
			} catch (Exception e) {
				area.setDeadline(null);
			}
			
			try {
				startdate = format.parse(c.getString(c.getColumnIndex(Area.FROM)));
				area.setFromDate(startdate);
			} catch (Exception e) {
				area.setFromDate(null);
			}
			
			area.setId(c.getLong(c.getColumnIndex(Area.ID)));
			area.setImg(c.getString(c.getColumnIndex(AreaLocal.IMG)));
			area.setLatitude(c.getDouble(c.getColumnIndex(Area.LATITUDE_COLUMN)));
			area.setLongitude(c.getDouble(c.getColumnIndex(Area.LONGITUDE_COLUMN)));
			
			try {
				moddate = format.parse(c.getString(c.getColumnIndex(Area.MODIFY)));
				area.setModifydate(moddate);
			} catch (Exception e) {
				area.setModifydate(null);
			}
			
			area.setName(c.getString(c.getColumnIndex(Area.NAME)));
			area.setTitle(c.getString(c.getColumnIndex(Area.TITLE)));
			area.setType(c.getInt(c.getColumnIndex(Area.TYPE)));
			areas.add(area);
		}
		c.close();
		return areas;
	}

}
